package com.webserver.http;

import javax.swing.text.html.parser.Entity;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

/*
响应对象
该类的每一个实例用于表示一个响应，每个响应由三个不封构成
1：状态行
2：响应头
 */
public class HttpServletResponse {
    //状态行的相关信息（定义）---属性
    private int statusCode = 200;
    private String statusReason = "ok";
    private String file;

    //响应头相关信息

    //响应正文相关信息
    private File entity;//响应正文对应的实体文件

    private Socket socket;
    //构造方法传进socket，不然下面的不认识
    public HttpServletResponse(Socket socket){
        this.socket = socket;
    }
    public void response() throws IOException {
         /*
                HTTP/1.1 200 OK(CRLF)
                Content-Type: text/html(CRLF)
                Content-Length: 2546(CRLF)(CRLF)
                1011101010101010101......
             */
        OutputStream out = socket.getOutputStream();
        //3.1发送状态行
        String line = "HTTP/1.1"+" "+statusCode+" "+statusReason;
        byte[] data = line.getBytes("ISO8859-1");
        out.write(data);
        out.write(13);//发送一个回车符
        out.write(10);//发送一个换行符

        //3.2发送响应头
        line = "Content-Type: text/html";
        data = line.getBytes("ISO8859-1");
        out.write(data);
        out.write(13);//发送一个回车符
        out.write(10);//发送一个换行符

        line = "Content-Length: " + file.length();
        data = line.getBytes("ISO8859-1");
        out.write(data);
        out.write(13);//发送一个回车符
        out.write(10);//发送一个换行符

        //单独发送CRLF表示响应头部分发送完毕
        out.write(13);//发送一个回车符
        out.write(10);//发送一个换行符

        //3.3发送响应正文
        FileInputStream fis = new FileInputStream(entity);
        int len;
        byte[] buf = new byte[1024*10];
        while((len = fis.read(buf))!=-1){
            out.write(buf,0,len);
        }
        System.out.println("响应发送完毕");
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public String getFile() {
        return file;
    }

    public void setFile(String file) {
        this.file = file;
    }

    public File getEntity() {
        return entity;
    }

    public void setEntity(File entity) {
        this.entity = entity;
    }
}
